package com.zbkj.crmeb.store.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.crmeb.core.annotation.UnitConvertUtil;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.TableNameUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.CrmebUtil;
import com.utils.DateUtil;
import com.utils.PriceUtil;
import com.utils.ProductUtil;
import com.utils.vo.dateLimitUtilVo;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelMemberLevel;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.MarkupRateTypeEnum;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.front.vo.RatioVo;
import com.zbkj.crmeb.member.enums.EquityTypeEnum;
import com.zbkj.crmeb.member.model.MerchantMemberBenefits;
import com.zbkj.crmeb.member.model.StoreProductDiscount;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.dao.StoreProductDraftDao;
import com.zbkj.crmeb.store.request.MarkupRateRequest;
import com.zbkj.crmeb.store.request.StoreProductAttrValueRequest;
import com.zbkj.crmeb.store.request.StoreProductSearchRequest;
import com.zbkj.crmeb.store.response.StoreProductAttrValueResponse;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.service.StoreProductAttrValueDraftService;
import com.zbkj.crmeb.store.service.StoreProductDraftService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.crmeb.store.service.SupplierService;
import com.zbkj.crmeb.user.model.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品草稿表 服务实现类
 * </p>
 *
 * @author wuzp
 * @since 2022-03-17
 */
@Service
@Slf4j
public class StoreProductDraftServiceImpl extends ServiceImpl<StoreProductDraftDao, StoreProductDraft> implements StoreProductDraftService {

    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private ICategoryMatchService categoryMatchService;
    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    private StoreProductAttrValueDraftService storeProductAttrValueDraftService;

    @Override
    public PageInfo<StoreProductResponse> getMerDraftList(StoreProductSearchRequest request, PageParamRequest pageParamRequest, Integer merId) {
        log.info("--------------- 查询商品列表, 当前的商户merId: {}, 查询条件: {} ---------------", merId, JSON.toJSONString(request));
        LambdaQueryWrapper<StoreProductDraft> lambdaQueryWrapper = getQueryWrapper(request, merId);
        Page<StoreProductDraft> storeProductPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<StoreProductDraft> productDraftList = this.list(lambdaQueryWrapper);
        if(CollectionUtils.isEmpty(productDraftList)) {
            return CommonPage.copyPageInfo(storeProductPage, new ArrayList<>());
        }
        List<Integer> ids = productDraftList.stream().map(StoreProductDraft::getId).collect(Collectors.toList());
        // 处理attrvalue数据
        List<StoreProductAttrValueDraft> attrValues = storeProductAttrValueDraftService.list(Wrappers.<StoreProductAttrValueDraft>lambdaQuery()
                .in(StoreProductAttrValueDraft :: getProductId, ids)
        );
        Map<Integer, List<StoreProductAttrValueResponse>> attrValueMap = attrValues.stream().collect(Collectors.toMap(StoreProductAttrValueDraft :: getProductId,
                s ->  {
                    List<StoreProductAttrValueResponse> list = new ArrayList<StoreProductAttrValueResponse>();
                    StoreProductAttrValueResponse response = new StoreProductAttrValueResponse();
                    BeanUtils.copyProperties(s, response);
                    list.add(response);
                    return list;
                },
                (List<StoreProductAttrValueResponse> value1, List<StoreProductAttrValueResponse> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        for(StoreProductDraft product : productDraftList) {
            Integer id = product.getId();
            // 对象复制
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);
            storeProductResponse.setAttrValue(attrValueMap.get(id));
            // 通过原价算折扣率 ----处理
            if (storeProductResponse.getOtPrice() != null && storeProductResponse.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(storeProductResponse.getCost(), storeProductResponse.getOtPrice(), storeProductResponse.getExchangeRate());
                if (null != bigDecimal) {
                    storeProductResponse.setDiscount(bigDecimal + "折");
                }
            }
            storeProductResponses.add(storeProductResponse);
        }
        return CommonPage.copyPageInfo(storeProductPage, storeProductResponses);
    }

    @Override
    public StoreProductResponse draftInfo(Integer id, Integer merId) {
        StoreProductDraft productDraft = this.getById(id);
        if (null == productDraft) {
            throw new CrmebException("未找到对应商品信息");
        }
        StoreProductResponse storeProductResponse = new StoreProductResponse();
        BeanUtils.copyProperties(productDraft, storeProductResponse);
        if(StringUtils.isNotBlank(productDraft.getCateId())){
            storeProductResponse.setCateId(Integer.parseInt(productDraft.getCateId()));
        }
        if(StringUtils.isNotBlank(productDraft.getSuppliersId())){
            storeProductResponse.setSuppliersId(Integer.parseInt(productDraft.getSuppliersId()));
        }
        storeProductResponse.setStockArea(StockAreaTempEnum.getByTempId(productDraft.getTempId()).getStockAreaCode());
        // 设置sku属性
        List<StoreProductAttrValueDraft> storeProductAttrValues = storeProductAttrValueDraftService.list(Wrappers.<StoreProductAttrValueDraft>lambdaQuery()
                .eq(StoreProductAttrValueDraft::getProductId,id));
        if (CollectionUtils.isEmpty(storeProductAttrValues)) {
            return storeProductResponse;
        }
        // H5 端用于生成skuList
        List<StoreProductAttrValueResponse> sPAVResponses = new ArrayList<>();
        for (StoreProductAttrValueDraft storeProductAttrValue : storeProductAttrValues) {
            StoreProductAttrValueResponse atr = new StoreProductAttrValueResponse();
            BeanUtils.copyProperties(storeProductAttrValue, atr);
            atr.setPrice(atr.getPrice().setScale(2, RoundingMode.HALF_UP));
            atr.setCost(atr.getCost().setScale(2, RoundingMode.HALF_UP));
            sPAVResponses.add(atr);
        }
        storeProductResponse.setAttrValue(sPAVResponses);
        return storeProductResponse;
    }

    private LambdaQueryWrapper<StoreProductDraft> getQueryWrapper(StoreProductSearchRequest request, Integer merId) {
        LambdaQueryWrapper<StoreProductDraft> lambdaQueryWrapper =  new LambdaQueryWrapper<>();
        //获取渠道商户信息
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        if(channelMerchant == null){
            throw new CrmebException("该商户不存在");
        }
//        List<String> brandIdsList= JSON.parseArray(channelMerchant.getBrandIds(), String.class);
//        List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
//        if(null!= brandIdsList && brandIdsList.size()>0){
//            lambdaQueryWrapper.in(StoreProductDraft::getBrandId,brandIdsList);
//        }
//        if(null!= tempIdList && tempIdList.size()>0){
//            lambdaQueryWrapper.in(StoreProductDraft::getTempId,tempIdList);
//        }
        lambdaQueryWrapper.eq(StoreProductDraft::getMerId,merId);
        //关键字搜索
        if (!StringUtils.isBlank(request.getKeywords())) {
            lambdaQueryWrapper.and(i -> i
                            .or().eq(NumberUtil.isInteger(request.getKeywords()), StoreProductDraft::getId, request.getKeywords())
                            .or().like(StoreProductDraft::getKeyword, request.getKeywords())
                            .or().like(StoreProductDraft::getStoreName, request.getKeywords())
            );
        }

        if (CollectionUtils.isNotEmpty(request.getStockAreas())) {
            lambdaQueryWrapper.in(StoreProductDraft::getTempId, request.getStockAreas());
        }
        if (StringUtils.isNotBlank(request.getBrandId())) {
            lambdaQueryWrapper.eq(StoreProductDraft::getBrandId, request.getBrandId());
        }
        if(CollectionUtils.isNotEmpty(request.getBrandIds())){
            lambdaQueryWrapper.in(StoreProductDraft::getBrandId,request.getBrandIds());
        }
        if (StringUtils.isNotBlank(request.getCateId())) {
            List<Integer> cateIds = categoryMatchService.getThreeChildVoListByPid(Integer.parseInt(request.getCateId())).stream().map(CategoryMatch::getId).collect(Collectors.toList());
            String cateIdStr = StringUtils.join(cateIds, ",");
            lambdaQueryWrapper.apply(CrmebUtil.getFindInSetSql("cate_id", cateIdStr));
        }
        if(CollectionUtils.isNotEmpty(request.getCateIds())){
            List<Integer> cateIds = new ArrayList<>();
            request.getCateIds().forEach(cateId->cateIds.addAll(categoryMatchService.getThreeChildVoListByPid(cateId).stream().map(CategoryMatch::getId).collect(Collectors.toList())));
            String cateIdStr = StringUtils.join(cateIds, ",");
            lambdaQueryWrapper.apply(CrmebUtil.getFindInSetSql("cate_id", cateIdStr));
        }

        // 最大小库存
        if(request.getMinStock() !=null && request.getMaxStock() == null){
            lambdaQueryWrapper.ge(StoreProductDraft::getStock,request.getMinStock());
        }else if(request.getMinStock() == null && request.getMaxStock() != null){
            lambdaQueryWrapper.le(StoreProductDraft::getStock,request.getMaxStock());
        }else if(request.getMinStock() !=null && request.getMaxStock() != null){
            lambdaQueryWrapper.between(StoreProductDraft::getStock,request.getMinStock(),request.getMaxStock());
        }
        if (null != request.getSeasonCode()) {
            if("-1".equals(request.getSeasonCode())) {
                lambdaQueryWrapper.isNull(StoreProductDraft::getSeasonCode);
            } else {
                lambdaQueryWrapper.likeRight(StoreProductDraft::getSeasonCode, request.getSeasonCode());
            }
        }
        //自建商品二手/新品查询
        if (Objects.equals(ProductTypeEnum.INSIDE.getCode(),request.getIsEurope())){
            if (Objects.equals(1,request.getOrderType())){
                lambdaQueryWrapper.and(i -> i.or().isNull(StoreProductDraft::getDegree).or().eq(StoreProductDraft::getDegree,""));
            }
            if (Objects.equals(3,request.getOrderType())){
                lambdaQueryWrapper.isNotNull(StoreProductDraft::getDegree).ne(StoreProductDraft::getDegree,"");
            }
        }
        if (request.isSellingBelowCost()) {
            lambdaQueryWrapper.apply(" price < cost ");
        }
        //过滤分类
//        List<String> cateIdList = categoryMatchService.selectCategoryMatchDisable(merId).stream().map(e -> e.getId().toString()).collect(Collectors.toList());
//        lambdaQueryWrapper.notIn(CollectionUtils.isNotEmpty(cateIdList), StoreProductDraft::getCateId, cateIdList);
        lambdaQueryWrapper.orderByDesc(StoreProductDraft::getId);
        return lambdaQueryWrapper;
    }

}
